"""
日志系统模块
提供统一的日志记录功能
"""

import logging
import logging.handlers
import os
from pathlib import Path
from typing import Optional
from .config import config


class Logger:
    """日志管理器"""
    
    def __init__(self, name: str = "subscription_system"):
        self.name = name
        self.logger = logging.getLogger(name)
        self._setup_logger()
        
    def _setup_logger(self):
        """设置日志器"""
        if self.logger.handlers:
            return  # 已经设置过了
            
        logging_config = config.get_logging_config()
        
        # 设置日志级别
        level = logging_config.get('level', 'INFO')
        self.logger.setLevel(getattr(logging, level.upper()))
        
        # 设置日志格式
        formatter = logging.Formatter(
            logging_config.get('format', 
                             '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        )
        
        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)
        
        # 文件处理器
        log_file = logging_config.get('file')
        if log_file:
            # 确保日志目录存在
            log_path = Path(log_file)
            log_path.parent.mkdir(parents=True, exist_ok=True)
            
            # 使用RotatingFileHandler支持日志轮转
            max_size = self._parse_size(logging_config.get('max_size', '10MB'))
            backup_count = logging_config.get('backup_count', 5)
            
            file_handler = logging.handlers.RotatingFileHandler(
                log_file, 
                maxBytes=max_size, 
                backupCount=backup_count,
                encoding='utf-8'
            )
            file_handler.setFormatter(formatter)
            self.logger.addHandler(file_handler)
            
    def _parse_size(self, size_str: str) -> int:
        """解析大小字符串为字节数"""
        size_str = size_str.upper()
        if size_str.endswith('KB'):
            return int(size_str[:-2]) * 1024
        elif size_str.endswith('MB'):
            return int(size_str[:-2]) * 1024 * 1024
        elif size_str.endswith('GB'):
            return int(size_str[:-2]) * 1024 * 1024 * 1024
        else:
            return int(size_str)
            
    def debug(self, message: str, *args, **kwargs):
        """记录调试信息"""
        self.logger.debug(message, *args, **kwargs)
        
    def info(self, message: str, *args, **kwargs):
        """记录信息"""
        self.logger.info(message, *args, **kwargs)
        
    def warning(self, message: str, *args, **kwargs):
        """记录警告"""
        self.logger.warning(message, *args, **kwargs)
        
    def error(self, message: str, *args, **kwargs):
        """记录错误"""
        self.logger.error(message, *args, **kwargs)
        
    def critical(self, message: str, *args, **kwargs):
        """记录严重错误"""
        self.logger.critical(message, *args, **kwargs)
        
    def exception(self, message: str, *args, **kwargs):
        """记录异常"""
        self.logger.exception(message, *args, **kwargs)


# 全局日志实例
logger = Logger()


def get_logger(name: str) -> Logger:
    """获取指定名称的日志器"""
    return Logger(name)
